<?php
// +------------------------------------------------------------------
// | Cls-Token [ USER LOGIN AUTHENTICATION TOKEN MIGRATION ]
// | Copyright (c) 2024 All rights reserved.
// | Based on ThinkPHP 6 | 8
// | Licensed Mulan PSL v2 ( http://license.coscl.org.cn/MulanPSL2 )
// | Author: CLS <422064377>
// +------------------------------------------------------------------

use think\migration\Migrator;
use Phinx\Db\Adapter\AdapterFactory;
use Phinx\Config\Config as PhinxConfig;

final class ##CLASS_NAME## extends Migrator
{
    public function init()
    {
        $options = $this->getDbConfig();

        $adapter = AdapterFactory::instance()
            ->getAdapter($options['adapter'], $options);

        if ($adapter->hasOption('table_prefix') || $adapter->hasOption('table_suffix')) {
            $adapter = AdapterFactory::instance()
                ->getWrapper('prefix', $adapter);
        }
        $adapter->connect();
        $this->setAdapter($adapter);
    }

    public function up()
    {
        ##DROP_TABLE##
        $this->table(
            '##TABLE_NAME##',
            [
                'id'          => false, // 不要自动创建主键id
                'primary_key' => 'user_identifier',
                'comment' => '// 用户token表_BY Cls-Token',
            ]
        )
            ->addColumn(
                'user_identifier',
                'string',
                [
                    'limit'   => 128,
                    'null'    => false,
                    'default' => '',
                    'comment' => '登录用户唯一标识(通常为用户表的id/uuid)',
                ]
            )
            ->addColumn(
                'token',
                'string',
                [
                    'limit'   => 500,
                    'null'    => false,
                    'default' => '',
                    'comment' => 'token令牌',
                ]
            )
            ->addColumn(
                'expire',
                'integer',
                [
                    'null'    => false,
                    'default' => 0,
                    'comment' => 'token令牌过期时间',
                ]
            )
            ->addColumn(
                'refresh_token',
                'string',
                [
                    'limit'   => 500,
                    'null'    => false,
                    'default' => '',
                    'comment' => 'refresh_token刷新令牌',
                ]
            )
            ->addColumn(
                'refresh_expire',
                'integer',
                [
                    "null"    => false,
                    'default' => 0,
                    'comment' => '刷新令牌过期时间',
                ]
            )
            ->addColumn(
                'ex_info',
                'string',
                [
                    'limit'   => 2000,
                    'null'    => false,
                    'default' => '',
                    'comment' => '登录用户其他信息(JSON字符串,不要放太多信息)',
                ]
            )
            ->addColumn(
                'user_agent',
                'string',
                [
                    'limit'   => 128,
                    'null'    => false,
                    'default' => '',
                    'comment' => '创建记录时的User-Agent(md5后的)',
                ]
            )
            ->addColumn(
                'ip',
                'string',
                [
                    'limit'   => 128,
                    'null'    => false,
                    'default' => '',
                    'comment' => '创建记录时的IP(注意移动应用后续来访IP可能会变,作校验时自行决定是否校验此字段)',
                ]
            )
            ->addColumn(
                'update_time',
                'integer',
                [
                    'null'    => false,
                    'default' => 0,
                    'comment' => '创建/更新token时的时间戳',
                ]
            )
            ->addIndex(
                'token',
                [
                    'name' => 'token_idx',
                    // 'unique'  => true,
                ]
            )
            ##REFRESH_INDEX##
            ->create();
    }

    public function down()
    {
        $this->table('##TABLE_NAME##')
            ->drop()
            ->save();
    }

    /**
     * 获取数据库配置
     * @return array
     */
    protected function getDbConfig(): array
    {

        $dbConnectKey = \think\facade\Config::get('database.default');

        $config = \think\facade\Config::get("database.connections.{$dbConnectKey}");

        if ($config['deploy'] == 0) {
            $dbConfig = [
                'adapter'      => $config['type'],
                'host'         => $config['hostname'],
                'name'         => $config['database'],
                'user'         => $config['username'],
                'pass'         => $config['password'],
                'port'         => $config['hostport'],
                'charset'      => $config['charset'],
                'suffix'       => $config['suffix'] ?? '',
                'table_prefix' => $config['prefix'],
            ];
        }
        else {
            $dbConfig = [
                'adapter'      => explode(',', $config['type'])[0],
                'host'         => explode(',', $config['hostname'])[0],
                'name'         => explode(',', $config['database'])[0],
                'user'         => explode(',', $config['username'])[0],
                'pass'         => explode(',', $config['password'])[0],
                'port'         => explode(',', $config['hostport'])[0],
                'charset'      => explode(',', $config['charset'])[0],
                'suffix'       => explode(',', $config['suffix'] ?? '')[0],
                'table_prefix' => explode(',', $config['prefix'])[0],
            ];
        }

        $table = \think\facade\Config::get('database.migration_table', 'migrations');

        $dbConfig['migration_table'] = $dbConfig['table_prefix'] . $table;
        $dbConfig['version_order']   = PhinxConfig::VERSION_ORDER_CREATION_TIME;

        return $dbConfig;
    }

}